import { defineStore } from 'pinia'
import { codeStore } from '__store/code'
import dt from '@dt/dt'
import router from '@/router'
import server from '@/config/server/index.js'

const key_user = 'user_info'
const key_history = 'user_history'
const key_role = 'user_role'

const api = {
  code: () => {
    return server.api().get('/sa-admin/api/v1/sysMenu/webMenuCode')
  },
  expireDate: () => {
    return server.api().get('/sa-admin/api/v1/sysUser/getUserPwdExpireDate')
  }
}

function expireDate() {
  return api
    .expireDate()
    .fetch({ userId: userStore().info.id })
    .then((res) => {
      if (userStore().expire != res) userStore().expire = res
    })
}

function update() {
  return api
    .code()
    .fetch()
    .then((res) => {
      let item = res.userVO
      userStore().info = item
      dt.session.set(key_user, item)
      if (userStore().history.accounts.indexOf(item.phone) < 0) {
        userStore().history.accounts.push(item.phone)
      }
      dt.storage.set(key_history, userStore().history)
      return res
    })
}

export const userStore = defineStore('user', {
  state: () => {
    return {
      role: dt.session.get(key_role),
      info: dt.session.get(key_user),
      history: dt.storage.get(key_history) || { accounts: [] },
      expire: null
    }
  },
  getters: {
    isLogin: (state) => {
      return state.info && codeStore().code
    }
  },
  actions: {
    choiceRole(item) {
      this.role = item
      dt.session.set(key_role, item)
    },
    update(type) {
      return codeStore()
        .updateCode(true)
        .then((res) => {
          if (type == 'login') expireDate()
          return res
        })
    },
    logout() {
      this.info = null
      this.role = null
      dt.session.remove(key_user)
      dt.session.remove(key_role)
      codeStore().clear()
      router.goLogin()
    },
    canShowMenu(code) {
      return codeStore().canShowMenu(code)
    },
    canShowButton(code) {
      return codeStore().canShowButton(code)
    }
  }
})

setTimeout(() => {
  codeStore().bingUpdateFunc(update)
  if (userStore().isLogin) {
    codeStore().updateCode(true)
  }
}, 1000)
